package com.xsjiong.hoofen;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.xsjiong.hoofen.entities.Exam;
import com.xsjiong.hoofen.entities.School;
import com.xsjiong.hoofen.entities.Student;

import java.util.ArrayList;
import java.util.Collection;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, ListView.OnItemClickListener {
	private ListView List;
	private ArrayAdapter<Exam> Adapter1;
	private ArrayList<Student> Data2 = new ArrayList<>();
	private StudentAdapter Adapter2;
	private ArrayList<Exam> Data1 = new ArrayList<>();
	private SwipeRefreshLayout RefreshLayout;
	private boolean Loading = false;
	private Exam CurrentExam;
	private int[] ClassFilter;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		List = new ListView(this);
		Adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Data1);
		List.setAdapter(Adapter1);
		List.setOnItemClickListener(this);
		RefreshLayout = new SwipeRefreshLayout(this);
		RefreshLayout.setColorSchemeColors(G.REFRESH_COLORS);
		RefreshLayout.addView(List);
		RefreshLayout.setOnRefreshListener(this);
		Adapter2 = new StudentAdapter(Data2);
		List.setDivider(null);
		setContentView(RefreshLayout);
		LoadData1();
	}

	@Override
	public void onRefresh() {
		if (CurrentExam == null)
			LoadData1();
		else LoadData2(ClassFilter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		if (CurrentExam == null) {
			final AppCompatEditText edit = new AppCompatEditText(this);
			edit.setHint("所有班级，以空格分割");
			final Exam chosen = Data1.get(position);
			edit.setText(chosen.getClassIDList());
			final AlertDialog cdialog = new AlertDialog.Builder(this).setTitle("请输入要查询的班级").setView(edit).setCancelable(true).setNegativeButton("取消", null).create();
			cdialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					UI.preventDismiss(cdialog);
					String str = edit.getText().toString().trim();
					for (int i = 0; i < str.length(); i++) {
						char c = str.charAt(i);
						if ((c < '0' || c > '9') && c != ' ') {
							edit.setError("含有非法字符");
							return;
						}
					}
					String[] tmp2 = str.split(" ");
					int[] tmp = new int[tmp2.length];
					int tot = 0;
					int q;
					for (int i = 0; i < tmp.length; i++) {
						q = Integer.parseInt(tmp2[i]);
						if (Exam.containsValue(tmp, q)) continue;
						if (!chosen.hasClass(q)) {
							edit.setError(tmp[i] + "班没有参加考试");
							return;
						}
						tmp[tot++] = q;
					}
					if (tot == 0)
						ClassFilter = chosen.getClassIDs();
					else {
						ClassFilter = new int[tot];
						System.arraycopy(tmp, 0, ClassFilter, 0, tot);
					}
					CurrentExam = chosen;
					Data2.clear();
					List.setAdapter(Adapter2);
					List.deferNotifyDataSetChanged();
					LoadData2(ClassFilter);
					UI.forceDismiss(cdialog);
				}
			});
			cdialog.show();
		} else {
			Student stu = Data2.get(position);
			new AlertDialog.Builder(this).setTitle(stu.name).setMessage(CurrentExam.getDescription(stu)).setCancelable(true).setPositiveButton("确定", null).show();
		}
	}

	private void LoadData2(final int[] clsIds) {
		if (Loading) return;
		Loading = true;
		RefreshLayout.setRefreshing(true);
		Data2.clear();
		Adapter2.notifyDataSetChanged();
		new Thread() {
			private Throwable t;

			@Override
			public void run() {
				try {
					Collection<Student> students = CurrentExam.getScores(clsIds);
					if (students == null) throw new RuntimeException("无网络连接");
					Data2.addAll(students);
					students = null;
					System.gc();
				} catch (Throwable t) {
					this.t = t;
				}
				Loading = false;
				UI.onUI(new Runnable() {
					@Override
					public void run() {
						RefreshLayout.setRefreshing(false);
						Adapter2.notifyDataSetChanged();
						if (t != null) UI.showError(MainActivity.this, t);
					}
				});
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		if (CurrentExam == null) finish();
		else {
			CurrentExam = null;
			Data2.clear();
			Adapter2.notifyDataSetChanged();
			List.setAdapter(Adapter1);
			Adapter1.notifyDataSetChanged();
		}
	}

	private void LoadData1() {
		if (Loading) return;
		Loading = true;
		RefreshLayout.setRefreshing(true);
		Data1.clear();
		Adapter1.notifyDataSetChanged();
		new Thread() {
			private Throwable t;

			@Override
			public void run() {
				try {
					Exam[] exams = School.DEFAULT.getAllExams();
					if (exams == null) throw new RuntimeException("无网络连接");
					for (int i = 0; i < exams.length; i++) Data1.add(exams[i]);
				} catch (Throwable t) {
					this.t = t;
				}
				Loading = false;
				UI.onUI(new Runnable() {
					@Override
					public void run() {
						RefreshLayout.setRefreshing(false);
						Adapter1.notifyDataSetChanged();
						if (t != null) UI.showError(MainActivity.this, t);
					}
				});
			}
		}.start();
	}
}